/*


 */

package jas.bank;

import jas.http.client.HttpClientImpl;
import jas.rpc.client.*;
import jas.rpc.http.RpcHttpClientFormatterImpl;
import jas.rpc.http.RpcHttpClientImpl;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import jas.rpc.RemoteException;

/**
 *
 *
 */
public class Client {
    
    private static void help() {
        System.out.println("Commands:");
        System.out.println("  login <name>       Login as <name> account.");
        System.out.println("  balance            Get balance of this account.");
        System.out.println("  deposit <amount>   Deposit <amount> into this account.");
        System.out.println("  withdraw <amount>  Withdraw <amount> from this account.");
    }
    
    public static void main(String[] args) throws RemoteException, IOException {
        String host = "localhost";
        if (args.length >= 1)
            host = args[0];
        
        int port = 8080;
        if (args.length >= 2)
            port = Integer.valueOf(args[1]);
        
        RpcClient client = new RpcHttpClientImpl(new HttpClientImpl(host, port), new RpcHttpClientFormatterImpl(new Base64ClientSerializer()), new StubFactoryImpl());
        
        Bank bank = client.getRemote(Bank.class, "bank");
        
        help();
        
        BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
        Account account = null;
        
        while (true) {
            String command = reader.readLine();
            if (command == null || command.length() == 0)
                continue;
            
            String[] parts = command.split(" ");
            String cmd = parts[0];
            
            if (cmd.equals("login") && parts.length >= 2) {
                account = bank.getAccount(parts[1]);
            }
            else if (cmd.equals("balance") && account != null) {
                System.out.println("Balance is " + account.getBalance());
            }
            else if (cmd.equals("deposit") && account != null && parts.length >= 2) {
                account.deposit(Double.valueOf(parts[1]));
            }
            else if (cmd.equals("withdraw") && account != null && parts.length >= 2) {
                account.withdraw(Double.valueOf(parts[1]));
            }
            else {
                System.out.println("What?");
                help();
            }
        }
    }
    
}
